<?php
namespace Admin\Model;
use Think\Model;
class PrivilegeModel extends Model 
{
	protected $insertFields = array('pri_name','module_name','controller_name','action_name','parent_id');
	protected $updateFields = array('id','pri_name','module_name','controller_name','action_name','parent_id');
	protected $_validate = array(
			array('pri_name', 'require', '权限名称不能为空！', 1, 'regex', 3),
			array('pri_name', '1,150', '权限名称的值最长不能超过 150 个字符！', 1, 'length', 3),
			array('module_name', '1,30', '模块名称的值最长不能超过 30 个字符！', 2, 'length', 3),
			array('controller_name', '1,30', '控制器名称的值最长不能超过 30 个字符！', 2, 'length', 3),
			array('action_name', '1,30', '方法名称的值最长不能超过 30 个字符！', 2, 'length', 3),
			array('parent_id', 'number', '上级权限ID，0：代表顶级分类必须是一个整数！', 2, 'regex', 3),
	);
	/************************************* 递归相关方法 *************************************/
	public function getTree()
	{
		$data = $this->select();
		return $this->_reSort($data);
	}
	private function _reSort($data, $parent_id=0, $level=0, $isClear=TRUE)
	{
		static $ret = array();
		if($isClear)
			$ret = array();
		foreach ($data as $k => $v)
		{
			if($v['parent_id'] == $parent_id)
			{
				$v['level'] = $level;
				$ret[] = $v;
				$this->_reSort($data, $v['id'], $level+1, FALSE);
			}
		}
		return $ret;
	}
	public function getChildren($id)
	{
		$data = $this->select();
		return $this->_children($data, $id);
	}
	private function _children($data, $parent_id=0, $isClear=TRUE)
	{
		static $ret = array();
		if($isClear)
			$ret = array();
		foreach ($data as $k => $v)
		{
			if($v['parent_id'] == $parent_id)
			{
				$ret[] = $v['id'];
				$this->_children($data, $v['id'], FALSE);
			}
		}
		return $ret;
	}
	// 判断管理员是否有权限访问这个页面
	public function chkPri()
	{
		// 获取当前管理员正要访问的模型名称、控制器名称、方法名称
		// tP中正带三个常量
		//MODULE_NAME , CONTROLLER_NAME , ACTION_NAME
		$adminId = session('id');
		// 如果是超级管理员直接返回 TRUE
		if($adminId == 29)
			return TRUE;
		$arModel = D('admin_role');
		$has = $arModel->alias('a')
		->join('LEFT JOIN s50_role_pri b ON a.role_id=b.role_id
		        LEFT JOIN s50_privilege c ON b.pri_id=c.id')
			        ->where(array(
			        		'a.admin_id' => array('eq', $adminId),
			        		'c.module_name' => array('eq', MODULE_NAME),
			        		'c.controller_name' => array('eq', CONTROLLER_NAME),
			        		'c.action_name' => array('eq', ACTION_NAME),
			        ))->count();
			        return ($has > 0);
	}
	

	
}